package com.xiaomaoguai.crs.common.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * webSocket配置类
 *
 * @ ClassName: WebSocketConfig.java
 * @ Author: WeiHui-Z
 * @ Date: 2016/12/22 12:53
 * @ Version: v1.0.0
 */
@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        HttpSessionHandshakeInterceptor handshakeInterceptor = new HttpSessionHandshakeInterceptor();
        registry.addHandler(textMessageHandler(), "/websocket").addInterceptors(handshakeInterceptor);
        //withSockJS允许客户端利用sockJs进行浏览器兼容性处理
        registry.addHandler(textMessageHandler(), "/websocket/socketjs").addInterceptors(handshakeInterceptor).withSockJS();

        Thread thread = new Thread(new HeartBeatCheckThread());
        thread.setName("HeartBeat");
        thread.start();
    }

    /**
     * @return TextMessageHandler
     */
    @Bean
    public TextMessageHandler textMessageHandler() {
        return new TextMessageHandler();
    }
}
